/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */

#ifndef BERT_MSGBUFFER_H
#define BERT_MSGBUFFER_H

#include <queue>
#include "Timer.h"
#include "Entry.h"

class MsgParse
{
public:
	virtual void msgParse(const void * cmd, unsigned int len ) = 0;
};

typedef std::pair<unsigned int, unsigned char *> CMD;
typedef std::pair<volatile bool, CMD> CMDPAIR;

class MsgBuffer : public MsgParse
{
	/**
	 * The size of msg array
	 */
	static const int ARRAYSIZE = 65536;
	/**
	 * Writable or readable flags
	 */
	static const bool WRITABLE = false;
	static const bool READABLE = true;
	/**
	 * Msg buffer
	 */
	CMDPAIR msgArray[ARRAYSIZE];
	/**
	 * The read and write pointer
	 */
	unsigned int readPtr;
	unsigned int writePtr;
	/**
	 * Backup queue
	 */
	std::queue<CMD> dumpQueue;
	/**
	 * Clear the buffer
	 */
	void finalClear();
public:
	/**
	 * Constructor
	 */
	MsgBuffer();
	/**
	 * Destructor
	 */
	~MsgBuffer();
	/**
	 * The logical thread fetch cmd
	 */
	CMD * get();
	/**
	 * After parse, the logical thread free the cmd
	 */
	void erase();
private:
	/**
	 * Move msg from dumpqueue to array
	 */
	bool moveToArray();
public:
	/**
	 * The IOthread put msg
	 */
	bool put(const void * cmd, unsigned int len);

	/**
	 * The logical thread retrieve msg and parse it
	 */
	void doCmd();
};

#endif

